<template lang="pug">
	.doctor-appointment-wrap
		main-header(placeholder="搜索医院" :rightText='rightText' @getValue="getSearch" @focus="inputFocus" @confirm="inputConfirm" @listenClick="cancel" ref="mainHeader")
		block(v-if="rightText.length")
			.search-wrap
				search-history
		block(v-else)
			.filter-wrap
				top-filter(:options="filterOptions" @getOptions="getOptions")
			scroll-view.hospital-list(scroll-y @scrolltolower="scrollToLower")
				no-item(text="暂无相关医院" v-if="noItem")
				hospital-item(:item="item" v-for="(item,index) in list" :key="index" @listenClick="goDetail(item)")

</template>

<script>
import mainHeader from '@/components/main-header'
import topFilter from '@/components/top-filter'
import noItem from '@/components/no-item'
import hospitalItem from '@/components/bespeak/hospital-item'
import searchHistory from '@/components/bespeak/search-history'
export default {
	name: 'bespeak',
	data() {
		return {
			filterOptions: [
				{
					actConIndex: 0,
					title: '全部',
					content: [
						{ title: '全部' },
						{ title: '椒江区', value: '331002' },
						{ title: '黄岩区', value: '331003' },
						{ title: '路桥区', value: '331004' },
						{ title: '玉环市', value: '331021' },
						{ title: '三门县', value: '331022' },
						{ title: '天台县', value: '331023' },
						{ title: '仙居县', value: '331024' },
						{ title: '温岭市', value: '331081' },
						{ title: '临海市', value: '331082' }
					]
				},
				{
					actConIndex: 0,
					title: '默认排序',
					content: [
						{ title: '默认排序' },
						{ title: '等级排序', value: '1' },
						{ title: '离我最近', value: '2' }
					]
				},
				{
					actConIndex: 0,
					title: '全部等级',
					content: [
						{ title: '全部等级' },
						{ title: '三级', value: '1' },
						{ title: '二级', value: '4' },
						{ title: '一级', value: '7' },
						{ title: '其他', value: '99' }
					]
				}
			],
			rightText: '',
			searchText: '',
			searchHistory: [],
			noItem: false,
			list: [],
			overFlag: false,
			page: 0,
			size: 12
		}
	},
	created() {},
	async mounted() {
		this.wx.showLoading({
			title: '加载中',
			icon: 'none'
		})
		await this.getLocation()
		await this.getRecentHospital()
		this.wx.hideLoading()
		//this.noItem = this.list.length <= 0
	},
	methods: {
		getLocation() {
			let x_PI = 3.14159265358979324 * 3000.0 / 180.0
			let that = this
			this.wx.getLocation({
				type: 'gcj02',
				success(res) {
					//获取坐标，转换坐标系到bd09
					let x = res.longitude,
						y = res.latitude
					let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_PI)
					let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_PI)
					that.longitude = z * Math.cos(theta) + 0.0065
					that.latitude = z * Math.sin(theta) + 0.006
					that.getHospital()
				},
				fail(res) {
					that.wx.showToast({
						title: '请允许小程序获取定位权限',
						icon: 'none'
					})
					setTimeout(() => {
						that.getHospital()
					}, 800)
				}
			})
		},
		async getOptions(options) {
			//筛选
			this.wx.showLoading({
				title: '加载中',
				icon: 'none'
			})
			this.orgLevel = options[2].content[options[2].actConIndex].value
			this.areaCode = options[0].content[options[0].actConIndex].value
			this.sort = options[1].content[options[1].actConIndex].value
			this.noItem = false
			this.list = this.tools.formatToArray(this.recentList || {})
			this.overFlag = false
			this.page = 0
			await this.getHospital()
			this.wx.hideLoading()
			this.noItem = this.list.length <= 0
		},
		async getRecentHospital() {
			let userInfo = this.wx.getStorageSync('userInfo'),
				hospitalId
			await this.api.jtApi
				.myOrder({
					access_token: userInfo.accessToken,
					member_num: userInfo.memberNum,
					res_type: '1',
					page_index: '1',
					page_size: '1'
				})
				.then(data => {
					if (data.ret_code === '0') {
						let list = data.records.record
						hospitalId = list.hospital_id
					}
				})
				.catch(() => {})

			await this.api.jtApi
				.hospitalInfo({
					hospital_id: hospitalId
				})
				.then(data => {
					if (data.ret_code === '0') {
						let hospital = data.hospital
						this.recentList = {
							orgIconUrl: hospital.hospital_picture,
							orgName: hospital.hospital_name,
							regDeptName: '无',
							levelText: hospital.hospital_level,
							orgCode: hospital.hospital_id,
							isRecent: true
						}
						this.list.unshift(this.recentList)
					}
				})
				.catch(() => {
					this.wx.hideLoading()
				})
		},
		async getHospital() {
			let levelMap = [
				'三级甲等',
				'三级乙等',
				'三级丙等',
				'二级甲等',
				'二级乙等',
				'二级丙等',
				'一级甲等',
				'一级乙等',
				'一级丙等'
			]
			this.page++
			let params = {
				page: this.page,
				size: this.size,
				resourcesType: 'Y'
			}

			this.orgLevel && Object.assign(params, { orgLevel: this.orgLevel })
			this.areaCode && Object.assign(params, { areaCode: this.areaCode })
			this.longitude &&
				Object.assign(params, {
					longitude: this.longitude,
					latitude: this.latitude
				})
			this.sort && Object.assign(params, { sort: this.sort })

			await this.api.tzApi
				.getHospital(params)
				.then(data => {
					if (data.responseFlag === '1') {
						this.overFlag = data.data.pages === data.data.current
						let records = this.tools.formatToArray(data.data.records)
						records.forEach(item => {
							item.levelText = levelMap[item.orgLevel] || '其他'
							item.regDeptName = item.regDeptName || '无'
						})
						this.list = this.list.concat(records)
					}
				})
				.catch(() => {
					this.wx.hideLoading()
					//this.noItem = this.list.length <= 0
				})
		},
		async scrollToLower() {
			if (!this.overFlag) {
				this.wx.showLoading({
					title: '加载中',
					icon: 'none'
				})
				await this.getHospital()
				this.wx.hideLoading()
				this.noItem = this.list.length <= 0
			}
		},
		getSearch(text) {
			this.searchText = text.toString()
		},
		inputFocus() {
			//唤起搜索键盘
			this.rightText = '取消'
			this.searchHistory = this.wx.getStorageSync('searchHistory').history || []
		},
		inputConfirm() {
			//搜索
			let history
			if (this.searchText.length) {
				let data = { name: this.searchText }
				history = _.uniqBy([data, ...this.searchHistory], 'name')
				this.wx.setStorage({
					key: 'searchHistory',
					data: {
						history: history
					}
				})
			}
		},
		cancel() {
			this.rightText = ''
		},
		goDetail(item) {
			this.$router.push({
				path: '/views/bespeak/selectDepartment',
				query: {
					hospitalId: item.orgCode,
					hospitalName: this.atob(item.orgName)
				}
			})
		}
	},
	components: {
		mainHeader,
		noItem,
		topFilter,
		searchHistory,
		hospitalItem
	}
}
</script>

<style lang="stylus">
	.doctor-appointment-wrap
		.filter-wrap,.search-wrap
			position fixed
			top 100px
			left 0
			width 100%
			z-index 10
		.hospital-list
			position absolute
			top 188px
			bottom 0
			left 0
			width 100%
		.search-wrap
			bottom 0
			background-color white
</style>
